package cn.usian.basicInformation.sensitivewords.config;

import cn.usian.pojo.basicInformation.sensitivewords.BaseSensitiveWords;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
 
/**
 * 敏感词过滤工具类
 * @author wuKeFan
 * @date 2023-03-02 13:45:19
 */
@Slf4j
@SuppressWarnings("unused")
public class SensitiveWordUtils {
 
    /**
     * 敏感词库
     */
    public static final Map<Object, Object> sensitiveWordMap = new HashMap<>();
 
    /**
     * 只过滤最小敏感词
     */
    public static int minMatchTYpe = 1;
 
    /**
     * 过滤所有敏感词
     */
    public static int maxMatchType = 2;
 
    /**
     * 初始化敏感词
     */
    public static void initKeyWord(List<BaseSensitiveWords> sensitiveWords) {
        try {
            // 从敏感词集合对象中取出敏感词并封装到Set集合中
            Set<String> keyWordSet = new HashSet<>();
            for (BaseSensitiveWords s : sensitiveWords) {
                keyWordSet.add(s.getSensitiveWords().trim());
            }
            // 将敏感词库加入到HashMap中
            addSensitiveWordToHashMap(keyWordSet);
        }
        catch (Exception e) {
            log.error("初始化敏感词出错,", e);
        }
    }
 
    /**
     * 封装敏感词库
     *
     * @param keyWordSet 敏感词库列表
     */
    private static void addSensitiveWordToHashMap(Set<String> keyWordSet) {
        // 敏感词
        String key;
        // 用来按照相应的格式保存敏感词库数据
        Map<Object, Object> nowMap;
        // 用来辅助构建敏感词库
        Map<Object, Object> newWorMap;
        // 使用一个迭代器来循环敏感词集合
        for (String s : keyWordSet) {
            key = s;
            // 等于敏感词库，HashMap对象在内存中占用的是同一个地址，所以此nowMap对象的变化，sensitiveWordMap对象也会跟着改变
            nowMap = sensitiveWordMap;
            for (int i = 0; i < key.length(); i++) {
                // 截取敏感词当中的字，在敏感词库中字为HashMap对象的Key键值
                char keyChar = key.charAt(i);
 
                // 判断这个字是否存在于敏感词库中
                Object wordMap = nowMap.get(keyChar);
                if (wordMap != null) {
                    nowMap = (Map<Object, Object>) wordMap;
                } else {
                    newWorMap = new HashMap<>();
                    newWorMap.put("isEnd", "0");
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }
 
                // 如果该字是当前敏感词的最后一个字，则标识为结尾字
                if (i == key.length() - 1) {
                    nowMap.put("isEnd", "1");
                }
                log.info("封装敏感词库过程：" + sensitiveWordMap);
            }
            log.info("查看敏感词库数据:" + sensitiveWordMap);
        }
    }
 
    /**
     * 敏感词库敏感词数量
     *
     * @return 返回数量
     */
    public static int getWordSize() {
        return SensitiveWordUtils.sensitiveWordMap.size();
    }
 
    /**
     * 是否包含敏感词
     *
     * @param txt 敏感词
     * @param matchType 匹配类型
     * @return 返回结果
     */
    public static boolean isContainSensitiveWord(String txt, int matchType) {
        boolean flag = false;
        for (int i = 0; i < txt.length(); i++) {
            int matchFlag = checkSensitiveWord(txt, i, matchType);
            if (matchFlag > 0) {
                flag = true;
            }
        }
        return flag;
    }
 
    /**
     * 获取敏感词内容
     *
     * @param txt 敏感词
     * @param matchType 匹配类型
     * @return 敏感词内容
     */
    public static Set<String> getSensitiveWord(String txt, int matchType) {
        Set<String> sensitiveWordList = new HashSet<>();
 
        for (int i = 0; i < txt.length(); i++) {
            int length = checkSensitiveWord(txt, i, matchType);
            if (length > 0) {
                // 将检测出的敏感词保存到集合中
                sensitiveWordList.add(txt.substring(i, i + length));
                i = i + length - 1;
            }
        }
        return sensitiveWordList;
    }
 
    /**
     * 替换敏感词
     *
     * @param txt 敏感词
     * @param matchType 匹配类型
     * @param replaceChar 代替词
     * @return 返回敏感词
     */
    public static String replaceSensitiveWord(String txt, int matchType, String replaceChar) {
        String resultTxt = txt;
        Set<String> set = getSensitiveWord(txt, matchType);
        Iterator<String> iterator = set.iterator();
        String word;
        String replaceString;
        while (iterator.hasNext()) {
            word = iterator.next();
            replaceString = getReplaceChars(replaceChar, word.length());
            resultTxt = resultTxt.replaceAll(word, replaceString);
        }
 
        return resultTxt;
    }
 
    /**
     * 替换敏感词内容
     *
     * @param replaceChar 需要替换的敏感词
     * @param length 替换长度
     * @return 返回结果
     */
    private static String getReplaceChars(String replaceChar, int length) {
        StringBuilder resultReplace = new StringBuilder(replaceChar);
        for (int i = 1; i < length; i++) {
            resultReplace.append(replaceChar);
        }
        return resultReplace.toString();
    }
 
    /**
     * 检查敏感词数量
     *
     * @param txt 敏感词
     * @param beginIndex 开始下标
     * @param matchType 匹配类型
     * @return 返回数量
     */
    public static int checkSensitiveWord(String txt, int beginIndex, int matchType) {
        boolean flag = false;
        // 记录敏感词数量
        int matchFlag = 0;
        char word;
        Map<Object, Object> nowMap = SensitiveWordUtils.sensitiveWordMap;
        for (int i = beginIndex; i < txt.length(); i++) {
            word = txt.charAt(i);
            // 判断该字是否存在于敏感词库中
            nowMap = (Map<Object, Object>) nowMap.get(word);
            if (nowMap != null) {
                matchFlag++;
                // 判断是否是敏感词的结尾字，如果是结尾字则判断是否继续检测
                if ("1".equals(nowMap.get("isEnd"))) {
                    flag = true;
                    // 判断过滤类型，如果是小过滤则跳出循环，否则继续循环
                    if (SensitiveWordUtils.minMatchTYpe == matchType) {
                        break;
                    }
                }
            }
            else {
                break;
            }
        }
        if (!flag) {
            matchFlag = 0;
        }
        return matchFlag;
    }
 
}